package com.tzx.fluttermixedapplication.test

import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking

// SharedFlow、StateFlow 是热流
// 热流是一种主动的数据流。它在创建时就开始发射事件，无论是否有观察者订阅。即使没有观察者，热流也会持续产生事件。
// 当观察者订阅时，它只是加入了已经运行的数据流，开始接收当前已经产生的事件。
// 缓存最近两次事件
// val sharedFlow = MutableSharedFlow<Int>(replay = 2)
val sharedFlow = MutableSharedFlow<Int>()
fun produceData() {
    // Simulating data emission
    sharedFlow.tryEmit(1)
    sharedFlow.tryEmit(2)
    sharedFlow.tryEmit(3)
}
fun consumeData() = flow {
    sharedFlow.collect { value ->
        emit(value)
    }
}
// Subscribing to the shared flow
fun testSharedFlow() {
    runBlocking {
        // Subscriber 1 received: 2
        // Subscriber 1 received: 3
        // Subscriber 2 received: 2
        // Subscriber 2 received: 3
        produceData()
        launch {
            consumeData().collect { value ->
                println("Subscriber 1 received: $value")
            }
        }
        // Subscriber 1 received: 2
        // Subscriber 1 received: 3
        // Subscriber 2 received: 2
        // Subscriber 2 received: 3
        // produceData()
        launch {
            consumeData().collect { value ->
                println("Subscriber 2 received: $value")
            }
        }
        // Subscriber 1 received: 2
        // Subscriber 1 received: 3
        // Subscriber 2 received: 2
        // Subscriber 2 received: 3
        // produceData()
    }
}

val stateFlow = MutableStateFlow(0)
fun updateState(newValue: Int) {
    stateFlow.value = newValue
}
fun observeState() = flow {
    stateFlow.collect { value ->
        emit(value)
    }
}
// Subscribing to the state flow
fun testStateFlow() {
    runBlocking {
        updateState(1)

        launch {
            observeState().collect { value ->
                //Subscriber received: 3
                println("Subscriber received: $value")
            }
        }
        updateState(2)
        updateState(3)
    }
}